﻿#region << 文 件 说 明 >>

/*----------------------------------------------------------------
// 文件名称：DataGridBehavior
// 创 建 者：杨程
// 创建时间：2021/12/2 15:06:45
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//
//
//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Core.WPF.Theme;

/// <summary>
/// DataGrid添加GroupBy功能
/// </summary>
public class DataGridGroupByBehavior : Behavior<DataGrid>
{
    /// <summary>
    /// 绑定分组名称
    /// </summary>
    public string GroupByPropertyNames { get; set; }

    /// <summary>
    /// 左间距
    /// </summary>
    public string MarginLeft { get; set; }

    protected override void OnAttached()
    {
        base.OnAttached();

        if (string.IsNullOrEmpty(GroupByPropertyNames))
        {
            return;
        }

        if (string.IsNullOrEmpty(MarginLeft))
        {
            MarginLeft = "0";
        }

        base.AssociatedObject.LoadingRow += AssociatedObject_LoadingRow;
    }



    private void AssociatedObject_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        

        if (base.AssociatedObject.GroupStyle.Count > 0)
        {
            // 如果已有分组样式，直接返回
            return;
        }

        var res = new ResourceDictionary() { Source = new Uri("pack://application:,,,/Vampirewal.Core.WPF.Theme;component/Theme.xaml", UriKind.RelativeOrAbsolute) };

        Style style = res["GroupHeaderStyle"] as Style;

        Style TargetStyle = null;

        var StyleStr = XamlWriter.Save(style);

        StyleStr = StyleStr.Replace("Tag=\"Target\"", "Margin=\"" + MarginLeft + " 0 0 0\" Text=\"{Binding Path=Name}\"");

        using (MemoryStream ms = new MemoryStream())
        {
            using (StreamWriter sw = new StreamWriter(ms))
            {
                sw.Write(StyleStr);
                sw.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                TargetStyle = XamlReader.Load(ms) as Style;
            }
        }

        base.AssociatedObject.GroupStyle.Clear();
        base.AssociatedObject.GroupStyle.Add(new GroupStyle()
        {
            ContainerStyle = TargetStyle,
        });

        

        // 添加分组描述
        ICollectionView view = CollectionViewSource.GetDefaultView(base.AssociatedObject.ItemsSource);
        if (view != null)
        {
            view.GroupDescriptions.Clear();
            foreach (var propertyName in GroupByPropertyNames.Split('-'))
            {
                view.GroupDescriptions.Add(new PropertyGroupDescription(propertyName));
            }
        }


        base.AssociatedObject.LoadingRow -= AssociatedObject_LoadingRow;
    }
}

/// <summary>
/// DataGrid添加分页功能
/// </summary>
public class DataGridPagination : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        //base.AssociatedObject.LoadingRow += AssociatedObject_LoadingRow;

        base.AssociatedObject.Loaded += AssociatedObject_Loaded;
        base.AssociatedObject.LoadingRow += AssociatedObject_LoadingRow;
    }

    private void AssociatedObject_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        base.AssociatedObject.LoadingRow -= AssociatedObject_LoadingRow;

        vp.SetValue(VPagination.IsShowPageDataCountSelectorProperty, true);
        vp.SetValue(VPagination.IsShowPageInfoProperty, true);
        vp.SetValue(VPagination.TotalDataCountProperty, base.AssociatedObject.Items.Count);
        vp.SetValue(VPagination.MaxShownPageCountProperty, 8);
        //vp.SetValue(VPagination.TotalDataCountProperty,100);
        vp.SetValue(VPagination.SelectedPageBackgroundProperty, Brushes.White);
        //vp.SetValue(VPagination.PageDataCountProperty, 1);
    }

    private ResourceDictionary res
    {
        get
        {
            return new ResourceDictionary() { Source = new Uri("pack://application:,,,/Vampirewal.Core.WPF.Theme;component/Theme.xaml", UriKind.RelativeOrAbsolute) };
        }
    }

    private VPagination vp = new VPagination();

    private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        base.AssociatedObject.Loaded -= AssociatedObject_Loaded;

        if (base.AssociatedObject.Parent != null)
        {
            var parent = base.AssociatedObject.Parent as Panel;
            parent.Children.Remove(base.AssociatedObject);

            Grid grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(100, GridUnitType.Auto) });
            grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(50) });
            Grid.SetRow(base.AssociatedObject, 0);
            grid.SetValue(Grid.BackgroundProperty, Brushes.Blue);
            grid.Children.Add(base.AssociatedObject);

            //Border border = new Border();
            //border.Background = new SolidColorBrush(Colors.Red);
            //border.Height = 50;
            //border.Margin = new Thickness(5);
            //Grid.SetRow(border, 1);

            //grid.Children.Add(border);

            vp.Style = res["VPaginationStyle"] as Style;
            vp.Height = 50;
            vp.HorizontalAlignment = HorizontalAlignment.Stretch;
            vp.Margin = new Thickness(5);
            Grid.SetRow(vp, 1);

            grid.Children.Add(vp);

            parent.Children.Add(grid);

            FrameworkElementFactory factory = new FrameworkElementFactory(typeof(Grid));
        }
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
    }
}